package ru.dc;

import com.sun.jndi.dns.DnsName;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import ru.dc.object.FavouriteHub;
import ru.dc.object.FavouriteHubListener;
import ru.dc.object.events.FavouriteHubEvent;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

/**
 * <pre>
 * User: Penkov Vladimir
 * Date: 08.11.2010
 * Time: 17:24:12
 * </pre>
 */
public class FavouriteServiceImpl implements FavouritesService {

    private List<FavouriteHub> favouriteHubs = new ArrayList<FavouriteHub>();
    private static final String FAVOURITE_FILENAME = "favourite.properties";
    private Log logger = LogFactory.getLog(getClass());
    private List<FavouriteHubListener> listeners = new ArrayList<FavouriteHubListener>();

    public void init() {
        File appDir = Application.getApplication().getApplicationHomeDir();
        File publicHubsList = new File(appDir, FAVOURITE_FILENAME);
        Properties p  = new Properties();
        try {
            p.load(new FileInputStream(publicHubsList));

            Map<String, Map<String, String>> attrsByNubNumber = new HashMap<String, Map<String, String>>();

            for (String key : p.stringPropertyNames()) {
                if (key.startsWith("hub.")) {
                    //hub.1.name=name1
                    final int numLastIndex = key.indexOf(".", 4);
                    String num = key.substring(4, numLastIndex);
                    String attrName = key.substring(numLastIndex+1);
                    Map<String, String> attrs = attrsByNubNumber.get(num);
                    if (attrs==null) {
                        attrs = new HashMap<String, String>();
                        attrsByNubNumber.put(num, attrs);
                    }
                    attrs.put(attrName, p.getProperty(key));
                }
            }

            for (Map<String, String> attrs : attrsByNubNumber.values()) {
                FavouriteHub hub = new FavouriteHub();
                hub.setName(attrs.get("name"));
                hub.setAutoConnect(Boolean.valueOf(attrs.get("autoconnect")));
                hub.getServerInfo().setAddress(attrs.get("address"));
                hub.getServerInfo().setPort(Integer.parseInt(attrs.get("port")));
                hub.getServerInfo().setNick(attrs.get("nick"));
                hub.getServerInfo().setEncoding(attrs.get("encoding"));
                favouriteHubs.add(hub);
            }

        } catch (IOException e) {
            logger.error("Can't load favourites hubs", e);
        }

    }


    public void addFavouriteHub(FavouriteHub hub) {
        favouriteHubs.add(hub);
        fireFavouriteHubAdded(hub);
        flush();
    }

    public void removeFavouriteHub(FavouriteHub hub) {
        favouriteHubs.remove(hub);
        fireFavouriteHubRemoved(hub);
        flush();
    }


    public void addFavouriteHubListener(FavouriteHubListener listener) {
        listeners.add(listener);
    }

    public void removeFavouriteHubListener(FavouriteHubListener listener) {
        listeners.remove(listener);
    }

    protected void fireFavouriteHubEvent(FavouriteHubEvent event) {
        for (FavouriteHubListener listener : listeners) {
            listener.onEvent(event);
        }
    }

    public void fireFavouriteHubAdded(FavouriteHub hub) {
        FavouriteHubEvent e = new FavouriteHubEvent(FavouriteHubEvent.FAVOURITE_HUB_ADDED, hub);
        fireFavouriteHubEvent(e);
    }

    public void fireFavouriteHubRemoved(FavouriteHub hub) {
        FavouriteHubEvent e = new FavouriteHubEvent(FavouriteHubEvent.FAVOURITE_HUB_REMOVED, hub);
        fireFavouriteHubEvent(e);
    }

    public List<FavouriteHub> getFavouriteHubs() {
        return favouriteHubs;
    }

    /**
     * Сохраняет хабы в файле.
     */
    private void flush() {
        File appDir = Application.getApplication().getApplicationHomeDir();
        File publicHubsList = new File(appDir, FAVOURITE_FILENAME);
        Properties p  = new Properties();
        int i = 0;
        for (FavouriteHub hub : favouriteHubs) {
            p.setProperty("hub."+i+".name", hub.getName());
            p.setProperty("hub."+i+".autoconnect", Boolean.toString(hub.isAutoConnect()));
            p.setProperty("hub."+i+".address",hub.getServerInfo().getAddress());
            p.setProperty("hub."+i+".port", Integer.toString(hub.getServerInfo().getPort()));
            if (!StringUtils.isEmpty(hub.getServerInfo().getNick())) {
                p.setProperty("hub."+i+".nick", hub.getServerInfo().getNick());
            }
            if (!StringUtils.isEmpty(hub.getServerInfo().getEncoding())) {
                p.setProperty("hub."+i+".encoding", hub.getServerInfo().getEncoding());
            }
            i++;
        }
        try {
            p.store(new FileOutputStream(publicHubsList), "favourites hubs");
        } catch (IOException e) {
            logger.error("Can't store favourites hubs", e);
        }


    }

}
